$(function() {
    var article = {
        swiper: '',
        itemIndex: 0,
        myScroll: '',
        init: function () {
            // 禁止微信webview网页下拉
            document.querySelector('body').addEventListener('touchmove', function(e) {
                e.preventDefault();
            })

            this.event();
        },
        event: function () {
            // 上拉下拉
            this.scrollData();

            // 初始化数据
            this.dataInit();

            // 初始化swiper
            this.swiper();

            // 头部导航初始化
            this.tabInit();

            // 头部导航点击事件
            this.tabClick();          
        },
        tabInit: function () {
            $('body').find('.nav_item').eq(0).addClass('tab-blue');            
        },
        // 初始化数据
        dataInit: function () {
            var that = this;            
            $('body').find('.swiper-slide').each(function (i, item) {

                var slug = $(this).attr('data-slug');
                var self = $(this).find('.list');
                var ajax = new AjaxHelper();
                
                if (slug) {
                    ajax.get('/article/type/'+slug, '', function (data) {
                        var results = data.results;

                        // 判断是否有值
                        if (results.length <= 0) {
                            self.append('<p class="noData">没有数据， 快发布一个吧 ~ </p>'); 
                            // 每次数据加载完，必须重置
                            that.myScroll.refresh()
                        } else {
                            $.each(results, function (i, item) {
                                var t = simpleTpl();
                                if (item.category_slug == slug) {
                                    if (item.elite == true) {
                                        var jh = '<i class="iconfont card-type card-type-jh">&#xe633;</i>';
                                    } else {
                                        var jh = '';
                                    }
                                    t._('<div class="list-item img-txt-list-item" data-path="/article/detail/'+item._id+'">')
                                        ._('<a href="/article/'+item._id+'">')
                                            ._('<div class="pull-right txt-item">')
                                                ._('<p class="item-title">'+item.title+'</p>')
                                                ._('<p class="item-desc">'+item.body+'</p>')
                                                ._('<div class="item-other">')
                                                    ._('<span class="author"><i class="iconfont">&#xe910;</i><b>'+item.author.username+'</b></span>')
                                                    ._('<span class="address"><i class="iconfont">&#xe939;</i>'+item.area+'</span>')
                                                    ._('<span class="date">'+moment(item.created_at,'YYYYMMDD').fromNow()+'</span>')
                                                    ._('<span class="comments"><i class="iconfont">&#xe957;</i><b>'+item.comments.length+'</b></span>')
                                                    ._('<span class="skim"><i class="iconfont">&#xe8db;</i><b>'+item.skim_num+'</b></span>')
                                                ._('</div>')
                                            ._('</div>')
                                            ._(jh)
                                        ._('</a>')
                                    t._('</div');
                                }
                                self.attr({
                                    'data-pageNumber': data.pageNumber,
                                    'data-pageCount': data.pageCount
                                });
                                self.append(t.toString());
                                // 每次数据加载完，必须重置
                                that.myScroll.refresh();
                                $.hideLoading();
                            });
                        }
                    });
                }
            });
        },
        swiper: function () {
            var self = this;
            self.swiper = new Swiper('.swiper-container',{
                // 自适应高
                autoHeight: true,
                onSlideChangeEnd: function (swiper) {
                    self.itemIndex = swiper.activeIndex;
                    $('#tab-top').find('.nav_item').removeClass('tab-blue');
                    $('#tab-top').find('.nav_item').eq(self.itemIndex).addClass('tab-blue');

                    self.slideDownFn();

                    // self.myScroll.refresh();
                    // $('body,html').animate({ scrollTop: 0 }, 1000);
                }
            });
            // 禁止触摸滑动
            // self.swiper.disableTouchControl();
        },
        tabClick: function () {
            var self = this;
            $('#tab-top').find('.nav_item').on('click', function () {
                // self.swiper.onResize();
                var index = $(this).index();
                self.itemIndex = index;
                // $('#tab-top').find('.nav_item').removeClass('tab-blue');
                // $(this).addClass('tab-blue');
                // 如果最后的参数为true 则调用onSlideChangeEnd回调函数
                self.swiper.slideTo(index, 1000, true);
            });
        },
        //滚动条监测
        scrollLook: function () {
            scroll(function(direction) { 
                // 正在向下滚
                if (direction == 'down') {
                    console.log("222")
                    // 头部导航
                    $('#tab-top').animate({top: '-44px'},300);
                    // 底部导航
                    // $('#tab-bottom').animate({bottom: '-55px'},300);
                }
                // 正在向上滚
                if (direction == 'up') {
                    // 头部导航
                    $('#tab-top').animate({top: '0px'},300);
                    // 底部导航
                    // $('#tab-bottom').animate({bottom: '0px'},300);
                }
            });    
            function scroll( fn ) {
                var $window = $(window),
                    beforeScrollTop = $window.scrollTop(),
                    fn = fn || function() {};

                $window.scroll(function() {                    
                    var afterScrollTop = $window.scrollTop(),
                        delta = afterScrollTop - beforeScrollTop;
                    if( delta === 0 ) return false;
                    fn( delta > 0 ? "down" : "up" );
                    beforeScrollTop = afterScrollTop;
                });
            }
        },
        scrollData: function () {
            var self = this;
                upIcon = $("#up-icon"),
                downIcon = $("#down-icon");
                
            self.myScroll = new IScroll('#wrapper', { probeType: 3, mouseWheel: true, preventDefault: false});
            
            self.myScroll.on("scroll",function(){
                var y = this.y,
                    maxY = this.maxScrollY - y,
                    downHasClass = downIcon.hasClass("reverse_icon"),
                    upHasClass = upIcon.hasClass("reverse_icon");
                
                if(y >= 40){
                    !downHasClass && downIcon.addClass("reverse_icon");
                    return "";
                }else if(y < 40 && y > 0){
                    downHasClass && downIcon.removeClass("reverse_icon");
                    return "";
                }
                
                if(maxY >= 40){
                    !upHasClass && upIcon.addClass("reverse_icon");
                    return "";
                }else if(maxY < 40 && maxY >=0){
                    upHasClass && upIcon.removeClass("reverse_icon");
                    return "";
                }
            });
            // 下拉
            self.myScroll.on("slideDown",function(){
                if(this.y > 40){
                    self.slideDownFn();
                }
            });
            
            self.myScroll.on("slideUp",function(){
                if(this.maxScrollY - this.y > 40){
                    var tabIndex = $('#tab-top').find('.nav_item.tab-blue').index(),
                        swiper = $('.swiper-container').find('.swiper-slide.swiper-slide-active'),
                        swiperIndex = swiper.index();
                    // 如果导航选中项和轮播选中项一样则进行下一步
                    if (tabIndex == swiperIndex) {
                        var slug = swiper.attr('data-slug');
                        var pageNumber = swiper.find('.list').attr('data-pagenumber');
                        var pageCount = swiper.find('.list').attr('data-pagecount');
                        console.log('slug:'+slug+'....pageNumber:'+pageNumber+'pageCount'+pageCount)
                        // 如果当前页为最后一页 则直接跳出
                        if (pageNumber == pageCount) {
                            $.toptips('没有数据了！');
                            self.myScroll.refresh();
                            return false;
                        }
                        var page = parseInt(pageNumber);
                        var ajax = new AjaxHelper();
                        ajax.get('/article/type/'+slug+'?page='+(++page)+'', '', function (data) {
                            $.hideLoading();
                            var results = data.results;
                            // swiper.find('.list').empty();
                            if (results.length > 0) {
                                $.each(results, function (i, item) {
                                    var t = simpleTpl();
                                    if (item.category_slug == slug) {
                                        if (item.elite == true) {
                                            var jh = '<i class="iconfont card-type card-type-jh">&#xe633;</i>';
                                        } else {
                                            var jh = '';
                                        }
                                        t._('<div class="list-item img-txt-list-item" data-path="article/'+item._id+'">')
                                            ._('<a href="/article/'+item._id+'">')
                                                ._('<div class="pull-right txt-item">')
                                                    ._('<p class="item-title">'+item.title+'</p>')
                                                    ._('<p class="item-desc">'+item.body+'</p>')
                                                    ._('<div class="item-other">')
                                                        ._('<span class="author"><i class="iconfont">&#xe910;</i><b>'+item.author.username+'</b></span>')
                                                        ._('<span class="address"><i class="iconfont">&#xe939;</i>'+item.area+'</span>')
                                                        ._('<span class="date">'+moment(item.created_at,'YYYYMMDD').fromNow()+'</span>')
                                                        ._('<span class="comments"><i class="iconfont">&#xe957;</i><b>'+item.comments.length+'</b></span>')
                                                        ._('<span class="skim"><i class="iconfont">&#xe8db;</i><b>'+item.skim_num+'</b></span>')
                                                    ._('</div>')
                                                ._('</div>')
                                                ._(jh)
                                            ._('</a>')
                                        t._('</div');
                                    }
                                    swiper.find('.list').attr({
                                        'data-pageNumber': data.pageNumber,
                                        'data-pageCount': data.pageCount
                                    });
                                    // 为了测试，延迟1秒加载
                                    setTimeout(function(){
                                        swiper.find('.list').append(t.toString());
                                        // 每次数据加载完，必须重置
                                        var h = $('body').find('.swiper-slide-active').height();
                                        $('.swiper-wrapper').css('height',h);
                                        self.myScroll.refresh();
                                        $.hideLoading();
                                    });
                                });
                            } else {
                                self.myScroll.refresh();
                                $.hideLoading();
                            }
                        }, function() {
                            $.toptips('数据获取失败！');
                            // 即使加载出错，也得重置
                            self.myScroll.refresh();
                            $.hideLoading();
                        });
                        upIcon.removeClass("reverse_icon")
                    }
                }
            });
        },
        slideDownFn: function () {
            var self = this;
                upIcon = $("#up-icon"),
                downIcon = $("#down-icon");

            var tabIndex = $('#tab-top').find('.nav_item.tab-blue').index(),
                swiper = $('.swiper-container').find('.swiper-slide.swiper-slide-active'),
                swiperIndex = swiper.index();
            // 如果当前头部导航选中项和轮播选中项一项则进行下一步
            if (tabIndex == swiperIndex) {
                // 获取当前选中文章类型
                var slug = swiper.attr('data-slug');
                var ajax = new AjaxHelper();
                // 获取当前类型文章集合
                ajax.get('/article/type/'+slug, '', function (data) {
                    var results = data.results;
                    // 如果结果长度大于0
                    if (data.results.length > 0) {
                        // 有结果就清空列表
                        swiper.find('.list').empty();
                        $.each(results, function (i, item) {
                            var t = simpleTpl();
                            if (item.category_slug == slug) {
                                if (item.elite == true) {
                                    var jh = '<i class="iconfont card-type card-type-jh">&#xe633;</i>';
                                } else {
                                    var jh = '';
                                }
                                t._('<div class="list-item img-txt-list-item">')
                                    ._('<a href="/article/'+item._id+'">')
                                        ._('<div class="pull-right txt-item">')
                                            ._('<p class="item-title">'+item.title+'</p>')
                                            ._('<p class="item-desc">'+item.body+'</p>')
                                            ._('<div class="item-other">')
                                                ._('<span class="author"><i class="iconfont">&#xe910;</i><b>'+item.author.username+'</b></span>')
                                                ._('<span class="address"><i class="iconfont">&#xe939;</i>'+item.area+'</span>')
                                                ._('<span class="date">'+moment(item.created_at,'YYYYMMDD').fromNow()+'</span>')
                                                ._('<span class="comments"><i class="iconfont">&#xe957;</i><b>'+item.comments.length+'</b></span>')
                                                ._('<span class="skim"><i class="iconfont">&#xe8db;</i><b>'+item.skim_num+'</b></span>')
                                            ._('</div>')
                                        ._('</div>')
                                        ._(jh)
                                    ._('</a>')
                                t._('</div');
                            }
                            swiper.find('.list').attr({
                                'data-pageNumber': data.pageNumber,
                                'data-pageCount': data.pageCount
                            });
                            // 为了测试，延迟1秒加载
                            setTimeout(function(){
                                swiper.find('.list').append(t.toString());
                                $.hideLoading();
                                // 每次数据加载完，必须重置
                                var h = $('body').find('.swiper-slide-active').height();
                                $('.swiper-wrapper').css('height',h);
                                self.myScroll.refresh()
                            },1000);
                        })
                    } else {
                        $.hideLoading();
                        // 每次数据加载完，必须重置
                        self.myScroll.refresh()
                        $.toptips('没有数据了 ～');
                    }
                }, function() {
                    $.toptips('数据获取失败！');
                    // 即使加载出错，也得重置
                    self.myScroll.refresh();
                    $.hideLoading();
                });
                upIcon.removeClass("reverse_icon");
            }
        }
    };

    article.init();
});